<template>
  <div class="productAndPrice-container">
    <div class="top-operation-container">
      <el-row>
        <el-col :span="4">
          <el-button
            v-auth="{v: ['crm:marketing:productPrice:create'], bool: disObj.show}"
            class="border-btn"
            size="mini"
            @click="create"
          >新建产品价格</el-button>
        </el-col>
        <el-col :span="20">
          <div style="display: flex; justify-content: flex-end">
            <el-form
              :model="formData"
              label-position="right"
              size="small"
              class="filter-form-inline"
            >
              <el-row
                :gutter="40"
                style="margin-left: 0px; margin-right: 0px"
              >
                <el-form-item
                  label="地区"
                  style="width:300px;margin-right:20px;"
                >
                  <el-cascader
                    ref="cascader"
                    v-model="formData.area"
                    :popper-append-to-body="false"
                    style="width: 100%;"
                    :options="citys"
                    placeholder="请选择适用地区"
                    :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
                    collapse-tags
                    clearable
                    @change="listSearch"
                    @visible-change="areaVisibleChange"
                  />
                </el-form-item>
                <el-form-item>
                  <filter-popover
                    ref="filterPopper"
                    right="20px"
                    :form-list="formList"
                    @onConfirm="filterDataConfirm"
                    @onReset="filterReset"
                    @show="filterPopperShow"
                  />
                </el-form-item>
                <el-form-item style="margin-left: 20px;">
                  <table-cell-setting
                    ref="tableCellSetting"
                    :table-option="tableOption"
                    :checked="checkListData"
                    @checkList="checkList"
                    @show="tableCellShow"
                  />
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>

    </div>
    <div class="table-list">
      <el-table
        header-cell-class-name="table-header"
        :data="productPriceListData"
        :border="true"
        :cell-style="cellStyle"
        @row-click="rowClick"
      >
        <el-table-column
          v-if="checkListData.indexOf('priceNumber') !== -1"
          prop="priceNumber"
          label="价格编号"
          fixed="left"
          :width="180"
          show-overflow-tooltip
          align="center"
          header-align="center"
        />
        <el-table-column
          v-if="checkListData.indexOf('region') !== -1"
          prop="region"
          label="适用地区"
          :min-width="150"
          :width="210"
          show-overflow-tooltip
          header-align="center"
        >
          <template #default="scope">
            <div>
              <area-list-view :areas="scope.row.region" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('accessMode') !== -1"
          prop="accessMode"
          label="准入模式"
          :width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="{row}">
            <span>{{ getLabel('access_mode',row.accessMode) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('priceType') !== -1"
          prop="priceType"
          label="价格属性"
          :width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="{row}">
            <span>{{ getLabel('price_type',row.priceType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('terminalType') !== -1"
          prop="terminalType"
          label="适用终端"
          :width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="{row}">
            <span>{{ getLabel('app_mode',row.terminalType) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('guidingPrice') !== -1"
          prop="guidingPrice"
          label="底价（元）"
          :width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="{row}">
            <span>{{ row.guidingPrice?row.guidingPrice:'未设置' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('marketPrice') !== -1"
          prop="marketPrice"
          label="市场价（元）"
          :width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          v-if="checkListData.indexOf('terminalPrice') !== -1"
          prop="terminalPrice"
          label="终端价（元）"
          :width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <!--
        <el-table-column
          v-if="checkListData.indexOf('priceSource') !== -1"
          prop="priceSource"
          label="价格来源"
          :width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="{row}">
            <span>{{ getLabel('price_source',row.priceSource) }}</span>
          </template>
        </el-table-column>
        -->
        <el-table-column
          v-if="checkListData.indexOf('createdAt') !== -1"
          prop="createdAt"
          label="创建时间"
          :width="140"
          header-align="center"
          align="center"
          sortable
        >
          <template #default="scope">
            <span>{{ dateFormat('yyyy-mm-dd HH:MM', scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('priceStrategyStatus') !== -1"
          prop="priceStrategyStatus"
          label="价格状态"
          :min-width="120"
          header-align="center"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <product-price-status
              style="line-height: 20px"
              :datas="scope.row"
              types="list"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-if="disObj.show"
          label="操作"
          fixed="right"
          header-align="center"
          :min-width="180"
        >
          <template #default="scope">
            <template v-if="scope.row.priceStrategyStatus!=='-4'&&scope.row.flowStatus!=='DOING'">
              <template v-if="scope.row.priceSource==='price_source'||scope.row.priceSource==='plan'&&scope.row.planInfo?.planStatus!=='3'">
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:edit'], bool: scope.row.priceStrategyStatus === '-1'||scope.row.flowStatus==='REJECT_INITIATOR'}"
                  type="text"
                  @click="editProductPrice(scope.row)"
                >编辑</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:change'], bool: scope.row.priceStrategyStatus === '2'}"
                  type="text"
                  @click="changePrice(scope.row)"
                >变更</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:zuofei'], bool: scope.row.priceStrategyStatus === '2'}"
                  type="text"
                  class="danger"
                  @click="obsoletePrice(scope.row)"
                >作废</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:delete'], bool: scope.row.priceStrategyStatus==='-1'||scope.row.priceStrategyStatus==='-2'||scope.row.priceStrategyStatus==='-4'}"
                  type="text"
                  class="danger"
                  @click="deleteProductPrice(scope.row)"
                >删除</el-button>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:page="formData.page"
        v-model:limit="formData.pageSize"
        style="display: flex; justify-content: flex-end"
        :total="total"
        @pagination="refreshList"
      />
    </div>
    <!-- 新建产品价格 -->
    <create-product-price
      ref="createProductPriceRef"
      @createEditSuccess="refreshList"
    />
    <!-- 变更产品价格 -->
    <change-product-price
      ref="changePriceRef"
      @changeSuccess="changeSuccess"
    />
    <!-- 作废产品价格 -->
    <obsolete-product-price
      ref="obsoletePriceRef"
      @obsoleteSuccess="obsoleteSuccess"
    />

    <!-- 产品价格详情 -->
    <detail-drawer
      ref="detailDrawer"
      custom-title
    >
      <template #title>
        <div
          class="draw-title"
          style="display:flex;justify-content:space-between;"
        >
          <div class="title-left">
            <span>产品价格 - {{ priceDetailRow.priceNumber }}</span>
            <product-price-status
              :datas="priceDetailRow"
              types="detail"
              style="margin-left:4px;"
            />
          </div>
          <div
            v-if="disObj.show"
            class="title-right"
          >
            <template v-if="priceDetailRow?.priceStrategyStatus!=='-4'&&priceDetailRow?.flowStatus!=='DOING'">
              <template v-if="priceDetailRow?.priceSource==='price_source'||priceDetailRow?.priceSource==='plan'&&priceDetailRow?.planInfo?.planStatus!=='3'">
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:edit'], bool: priceDetailRow?.priceStrategyStatus === '-1'||priceDetailRow?.flowStatus==='REJECT_INITIATOR'}"
                  type="primary"
                  size="small"
                  @click="editProductPrice(priceDetailRow)"
                >编辑</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:change'], bool: priceDetailRow?.priceStrategyStatus === '2'}"
                  type="primary"
                  size="small"
                  @click="changePrice(priceDetailRow)"
                >变更</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:zuofei'], bool: priceDetailRow?.priceStrategyStatus === '2'}"
                  type="primary"
                  size="small"
                  class="danger"
                  @click="obsoletePrice(priceDetailRow)"
                >作废</el-button>
                <el-button
                  v-auth="{v: ['crm:marketing:productPrice:delete'], bool: priceDetailRow?.priceStrategyStatus==='-1'||priceDetailRow?.priceStrategyStatus==='-2'||priceDetailRow?.priceStrategyStatus==='-4'}"
                  type="primary"
                  size="small"
                  class="danger"
                  @click="deleteProductPrice(priceDetailRow)"
                >删除</el-button>
              </template>
            </template>
          </div>
        </div>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <item-title title="基本信息" />
            <client-price-base-info
              :product-detail="detail"
              :price-detail="priceDetailRow"
            />
          </div>
          <div class="history-list">
            <item-title title="修改记录" />
            <operation-view
              :id="priceDetailRow?.id"
              mode="product_price"
            />
          </div>
        </div>
      </template>
    </detail-drawer>

  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue'
import area from '@/utils/area.js'
import { crmStore } from '@CRM/store'
import { useRoute } from 'vue-router'

export default {
  components: {
    createProductPrice: defineAsyncComponent(() =>
      import('./createProductPrice/index.vue')
    ),
    changeProductPrice: defineAsyncComponent(() =>
      import('./changeProductPrice/index.vue')
    ),
    obsoleteProductPrice: defineAsyncComponent(() =>
      import('./obsoleteProductPrice/index.vue')
    ),
    ClientPriceBaseInfo: defineAsyncComponent(() =>
      import('./modules/clientPriceBaseInfo.vue')
    ),
    productPriceStatus: defineAsyncComponent(() =>
      import('./modules/productPriceStatus.vue')
    ),
  },
  props: {
    detail: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, context) {
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const citys = area
    var createProductPriceRef = ref(null)
    var changePriceRef = ref(null)
    var obsoletePriceRef = ref(null)
    var cascader = ref(null)
    var detailDrawer = ref(null)
    var productDetail = reactive(props.detail)
    var productPriceData = reactive({
      disObj: { show: true, msg: '' },
      filterPopper: null,
      tableCellSetting: null,
      total: 0,
      formData: {
        page: 1,
        pageSize: 20,
        productId: Number(route.query.productId),
        area: [],
        accessMode: '',
        priceType: '',
        priceSource: '',
        terminalType: '',
        max: 0,
        min: 0,
        startTime: null,
        endTime: null,
        priceStrategyStatus: '',
      },
      productPriceListData: [],
      priceDetailRow: null,
      tableOption: [
        {
          key: 'priceNumber',
          value: '价格编号',
        },
        {
          key: 'accessMode',
          value: '准入模式',
        },
        {
          key: 'region',
          value: '适用地区',
        },
        {
          key: 'priceType',
          value: '价格属性',
        },
        {
          key: 'terminalType',
          value: '适用终端',
        },
        {
          key: 'marketPrice',
          value: '市场价格',
        },
        {
          key: 'terminalPrice',
          value: '终端价',
        },
        {
          key: 'guidingPrice',
          value: '底价',
        },
        // {
        //   key: 'priceSource',
        //   value: '价格来源',
        // },
        {
          key: 'createdAt',
          value: '创建时间',
        },
        {
          key: 'priceStrategyStatus',
          value: '状态',
        },
      ],
      formList: [
        {
          key: 'priceStrategyStatus',
          label: '价格状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options:
            crmStore.getters['dictionary/getDictionary'][
              'product_price_status'
            ],
        },
        {
          key: 'accessMode',
          label: '准入模式',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['access_mode'],
        },
        {
          key: 'priceType',
          label: '价格属性',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['price_type'],
        },
        {
          key: 'terminalType',
          label: '适用终端',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['app_mode'],
        },
        // {
        //   key: 'priceSource',
        //   label: '价格来源',
        //   form_type: 'select',
        //   value: '',
        //   is_search: false,
        //   options: crmStore.getters['dictionary/getDictionary']['price_source'],
        // },
        {
          key: 'priceRange',
          label: '终端价范围',
          form_type: 'pricerange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'dateRange',
          label: '创建时间',
          form_type: 'daterange',
          value: [],
          is_search: false,
          options: [],
        },
      ],
    })
    var checkListData = ref([
      'priceNumber',
      'accessMode',
      'region',
      'priceType',
      'terminalType',
      'marketPrice',
      'terminalPrice',
      'guidingPrice',
      'createdAt',
      'priceStrategyStatus',
    ])
    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event)
      if (column.label === '操作') return
      productPriceData.priceDetailRow = row
      detailDrawer.value.open()
    }
    const checkList = (checked) => {
      checkListData.value = checked
      console.log(checkListData)
    }
    // 搜索
    const listSearch = (val) => {
      productPriceData.formData.page = 1
      productPriceData.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
      getProductPriceList()
    }
    // 获取产品价格列表
    const getProductPriceList = () => {
      api.product.PRODUCT_PRICE_LIST(productPriceData.formData).then((res) => {
        if (res.code === 0) {
          productPriceData.productPriceListData = res.data.list
          productPriceData.total = res.data.total
          // 判断抽屉的数据不为空的话，更新数据
          if (productPriceData.priceDetailRow) {
            productPriceData.priceDetailRow =
              productPriceData.productPriceListData.find(
                (p) => p.id === productPriceData.priceDetailRow.id
              )
          }
        }
      })
    }
    const filterPopperShow = () => {
      productPriceData.tableCellSetting.close()
    }
    const tableCellShow = () => {
      productPriceData.filterPopper.close()
    }
    const areaVisibleChange = (val) => {
      if (val) {
        productPriceData.filterPopper.close()
      }
    }
    const filterReset = () => {
      productPriceData.formData = {
        productId: productDetail.id,
        area: [],
        accessMode: '',
        priceType: '',
        priceSource: '',
        terminalType: '',
        max: 0,
        min: 0,
        startTime: null,
        endTime: null,
        priceStrategyStatus: '',
        page: 1,
        pageSize: 20,
      }
      getProductPriceList()
    }
    const filterDataConfirm = (formdata) => {
      productPriceData.formData.accessMode = formdata.accessMode
      productPriceData.formData.priceType = formdata.priceType
      productPriceData.formData.terminalType = formdata.terminalType
      productPriceData.formData.priceSource = formdata.priceSource
      productPriceData.formData.max =
        formdata.priceRange && formdata.priceRange.length
          ? formdata.priceRange[1]
          : 0
      productPriceData.formData.min =
        formdata.priceRange && formdata.priceRange.length
          ? formdata.priceRange[0]
          : 0
      productPriceData.formData.startTime =
        formdata.dateRange && formdata.dateRange.length
          ? formdata.dateRange[0]
          : null
      productPriceData.formData.endTime =
        formdata.dateRange && formdata.dateRange.length
          ? formdata.dateRange[1]
          : null
      productPriceData.formData.priceStrategyStatus =
        formdata.priceStrategyStatus

      getProductPriceList()
    }
    // 判断操作按钮是否可用
    const isCreatePrice = () => {
      if (productDetail.productStatus === '-1') {
        productPriceData.disObj.show = false
        productPriceData.disObj.msg = '产品审核未通过，暂不支持创建产品价格'
      }
      if (productDetail.productStatus === '-4') {
        productPriceData.disObj.show = false
        productPriceData.disObj.msg = '产品已下架'
      }
      if (productDetail.productStatus === '1') {
        productPriceData.disObj.show = false
        productPriceData.disObj.msg = '产品审核中'
      }
      console.log(productPriceData.disObj.show)
    }
    // 新建产品价格
    const create = () => {
      createProductPriceRef.value.open('create', {
        productDetail: productDetail,
      })
    }
    // 编辑产品价格
    const editProductPrice = (row) => {
      createProductPriceRef.value.open('edit', {
        productDetail: productDetail,
        priceDetail: {
          ...row,
        },
      })
    }
    // 更新列表
    const refreshList = () => {
      getProductPriceList()
    }
    // 变更产品价格
    const changePrice = (row) => {
      if (row.priceSource === 'plan' && row.planStatus === '3') {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '该终端价关联招商计划目前仍在招商中，暂时不支持变更价格。',
        })
        return false
      }
      changePriceRef.value.open({
        productDetail: productDetail,
        priceDetail: {
          ...row,
        },
      })
    }
    // 变更操作成功
    const changeSuccess = () => {
      getProductPriceList()
    }
    // 作废产品价格
    const obsoletePrice = (row) => {
      if (row.priceSource === 'plan' && row.planStatus === '3') {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '该终端价关联招商计划目前仍在招商中，暂时不支持作废价格。',
        })
        return false
      }
      obsoletePriceRef.value.open({
        productDetail: productDetail,
        priceDetail: {
          ...row,
        },
      })
    }
    // 作废成功
    const obsoleteSuccess = () => {
      getProductPriceList()
    }
    // 删除产品价格
    const deleteProductPrice = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '数据删除后不可恢复，确定删除？',
          title: '产品价格删除',
        })
        .then(() => {
          api.product
            .DELETE_PRODUCT_PRICE({
              id: row.id,
            })
            .then((res) => {
              if (res.code === 0) {
                getProductPriceList()
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
        })
        .catch((err) => {
          console.log(err)
        })
    }
    onMounted(() => {
      getProductPriceList()
    })
    watch(
      () => props.detail,
      (newval, oldval) => {
        if (newval) {
          productDetail = newval
          isCreatePrice()
        }
      },
      {
        immediate: true,
      }
    )
    return {
      detailDrawer,
      productDetail,
      citys,
      createProductPriceRef,
      changePriceRef,
      obsoletePriceRef,
      cascader,
      editProductPrice,
      changePrice,
      ...toRefs(productPriceData),
      checkListData,
      checkList,
      deleteProductPrice,
      cellStyle,
      rowClick,
      listSearch,
      isCreatePrice,
      create,
      obsoletePrice,
      refreshList,
      obsoleteSuccess,
      changeSuccess,
      filterDataConfirm,
      filterReset,
      filterPopperShow,
      tableCellShow,
      areaVisibleChange,
    }
  },
}
</script>

<style lang="scss" scoped>
@import "@CRM/assets/scss/views/product/productAndPrice.scss";
</style>
